<template>
  <div class="application-container">
    <!-- 选项卡 -->
    <el-tabs v-model="activeName" @tab-change="handleTabChange">
      <el-tab-pane label="待处理" name="0" />
      <el-tab-pane label="已通过" name="1" />
      <el-tab-pane label="已拒绝" name="2" />
    </el-tabs>

    <!-- 搜索 -->
    <div class="formSearch">
      <el-form :inline="true" :model="searchData">
        <el-form-item label="商家名称">
          <el-input v-model="searchData.shopName" maxlength="20" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="注册手机号">
          <el-input v-model="searchData.shopPhone" maxlength="11" placeholder="请输入注册手机号" />
        </el-form-item>
        <el-form-item label="店铺类型">
          <el-select v-model="searchData.authenType" clearable placeholder="请选择店铺类型">
            <el-option label="个人" :value="1" />
            <el-option label="个体工商户" :value="2" />
            <el-option label="企业" :value="3" />
            <el-option label="其他组织" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchData.dates"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading.table"
        :data="tableData"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        tooltip-effect="dark"
        :style="{ width: '100%' }"
        class="dataTable"
      >
      <el-table-column label="商家名称" width="220">
        <template #default="scope">{{ scope.row.shopName }}</template>
      </el-table-column>
      <el-table-column label="店铺类型">
        <template #default="scope">
          <span v-if="scope.row.authenType == 1">个人</span>
          <span v-else-if="scope.row.authenType == 2">个体工商户</span>
          <span v-else-if="scope.row.authenType == 3">企业</span>
          <span v-else-if="scope.row.authenType == 4">其他组织</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="shopPhone" label="注册手机号" />
      <el-table-column prop="createTime" label="申请时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <div class="btnList">
            <el-button
              v-if="activeName === '0'"
              link
              type="primary"
              @click="handleProcess(scope.row)"
              >处理</el-button
            >
            <el-button
              v-if="activeName === '1' || activeName === '2'"
              link
              type="primary"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              v-if="activeName === '1' || activeName === '2'"
              link
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="searchData.page"
        v-model:page-size="searchData.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processVisible"
      title="入驻申请处理"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="processFormRef" :model="processForm" :rules="processRules" label-width="100px">
        <el-form-item label="处理结果" prop="state">
          <el-radio-group v-model="processForm.state">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="processForm.state === 2" label="拒绝原因" prop="reason">
          <el-input
            v-model="processForm.reason"
            type="textarea"
            maxlength="200"
            :rows="4"
            placeholder="请输入拒绝原因"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitProcess"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="入驻申请详情" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="商家名称">{{ detailData.shopName }}</el-descriptions-item>
        <el-descriptions-item label="注册手机号">{{ detailData.shopPhone }}</el-descriptions-item>
        <el-descriptions-item label="店铺类型">
          <span v-if="detailData.authenType == 1">个人</span>
          <span v-else-if="detailData.authenType == 2">个体工商户</span>
          <span v-else-if="detailData.authenType == 3">企业</span>
          <span v-else-if="detailData.authenType == 4">其他组织</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag v-if="detailData.state === 0" type="info">待处理</el-tag>
          <el-tag v-else-if="detailData.state === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="detailData.state === 2" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailData.state === 2" label="拒绝原因">{{
          detailData.reason
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { BusinessService } from '@/api/businessApi'
  import type {
    ShopCheckType,
    CheckGetAllParam,
    CheckHandleParam,
    CheckDeleteParam,
    CheckGetByIdParam
  } from '@/api/model/businessModel'

  // 表格相关
  const loading = ref({
    table: false
  })
  const tableData = ref<ShopCheckType[]>([])
  const total = ref(0)

  // 搜索表单
  const activeName = ref('0')
  const searchData = reactive<CheckGetAllParam>({
    page: 1,
    pageSize: 10,
    shopName: '',
    shopPhone: '',
    authenType: undefined, // 店铺类型筛选
    dates: [],
    checkState: 0 // 根据tab切换更新，后端使用checkState字段
  })

  // 对话框相关
  const processVisible = ref(false)
  const detailVisible = ref(false)
  const submitLoading = ref(false)

  // 表单引用
  const processFormRef = ref()

  // 处理表单数据
  const processForm = reactive<CheckHandleParam>({
    shopId: 0,
    state: 1, // 1-通过 2-拒绝
    reason: ''
  })

  // 详情数据
  const detailData = ref<ShopCheckType>({})

  // 表单验证规则
  const processRules = {
    state: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
    reason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
  }

  // 处理tab切换
  const handleTabChange = (name: string) => {
    searchData.checkState = parseInt(name)
    searchData.page = 1
    getAll()
  }

  // 获取入驻申请列表
  const getAll = async () => {
    loading.value.table = true
    try {
      const res = await BusinessService.checkGetAll(searchData)
      if (res.code === '200') {
        tableData.value = res.data.list
        total.value = res.data.total
      } else {
        ElMessage.error(res.message || '获取入驻申请列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取入驻申请列表失败')
    } finally {
      loading.value.table = false
    }
  }

  // 处理查询
  const search = () => {
    searchData.page = 1
    getAll()
  }

  // 处理分页
  const handleSizeChange = (val: number) => {
    searchData.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    searchData.page = val
    getAll()
  }

  // 处理入驻申请
  const handleProcess = (row: ShopCheckType) => {
    processForm.shopId = row.shopId!
    processForm.state = 1
    processForm.reason = ''
    processVisible.value = true
  }

  // 查看详情
  const handleView = async (row: ShopCheckType) => {
    try {
      const res = await BusinessService.checkGetById({ shopId: row.shopId! } as CheckGetByIdParam)
      if (res.data.code === '200') {
        detailData.value = res.data.data
        detailVisible.value = true
      } else {
        ElMessage.error(res.data.message || '获取详情失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取详情失败')
    }
  }

  // 删除入驻申请
  const handleDelete = (row: ShopCheckType) => {
    ElMessageBox.confirm('确认要删除该入驻申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const res = await BusinessService.checkDelete({ shopId: row.shopId! } as CheckDeleteParam)
          if (res.data.code === '200') {
            ElMessage.success('删除成功')
            getAll()
          } else {
            ElMessage.error(res.data.message || '删除失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 提交处理结果
  const submitProcess = () => {
    if (!processFormRef.value) return
    processFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        submitLoading.value = true
        try {
          // 如果是通过状态，不需要拒绝原因
          const params: CheckHandleParam = {
            shopId: processForm.shopId,
            state: processForm.state,
            reason: processForm.state === 2 ? processForm.reason : undefined
          }

          const res = await BusinessService.checkHandle(params)
          if (res.data.code === '200') {
            ElMessage.success('处理成功')
            processVisible.value = false
            getAll()
          } else {
            ElMessage.error(res.data.message || '处理失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('处理失败')
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 初始化
  onMounted(() => {
    getAll()
  })
</script>

<style lang="scss" scoped>
  .application-container {
    padding: 20px;
    background-color: #fff;

    .formSearch {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .table-container {
      margin-bottom: 20px;
      overflow-x: auto;
      overflow-y: auto;
      touch-action: pan-y;
      -webkit-overflow-scrolling: touch;
    }

    .dataTable {
      margin-bottom: 0;
      width: 100%;
    }

    .pagination-wrapper {
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      touch-action: pan-x;
      -webkit-overflow-scrolling: touch;
      padding: 10px 0;
      justify-content: flex-start;
      
      ::v-deep .el-pagination {
        display: flex;
        justify-content: flex-start;
        min-width: auto !important;
        margin: 0 !important;
        padding: 0 10px !important;
      }
      
      ::v-deep .el-pagination__sizes {
        margin-right: 10px;
      }
      
      ::v-deep .el-pagination__total {
        margin-right: 10px;
      }
      
      ::v-deep .el-pagination__jump {
        margin-left: 10px;
      }
    }

    .btnList {
      display: flex;
      gap: 10px;
    }

    .dialog-footer {
      text-align: right;
    }
  }

  @media screen and (max-width: $device-phone) {
    .application-container {
      padding: 10px;

      .formSearch {
        padding: 15px;

        :deep(.el-form-item) {
          margin-bottom: 15px;
        }
      }
    }
  }
</style>
